# Define the couchapp design doc
# Change the last part of the _id value to something specific to the couchapp.
#
design_doc =
	_id: '_design/app'

	rewrites: [
		{ from: "/", to: 'index.html' }
		{ from: "/*", to: '*' }
		{ from: "/api", to: '../../' }
		{ from: "/api/*", to: '../../*' }
	]

	validate_doc_update: (newDoc, oldDoc, userCtx) ->
		if newDoc._deleted is true and userCtx.roles.indexOf('_admin') is -1
			throw "Only admin can delete documents on this database."

	views:
		all:
			map: (doc) -> emit null, doc

		'Patrons per capita':
			map: (doc) ->
				if doc.Sheetname is 'Registration'
					k = doc['Library System']
					return if k is 'All Libraries'
					v =
						pop: doc['Population served']
						patrons: doc['Total active cardholders at year end1']
					v.percap = 100 * v.patrons / v.pop
					emit k, v

		'Circulations per capita':
			map: (doc) ->
				if doc.Sheetname is 'Circulation'
					k = doc['Library System']
					return if k is 'All Libraries'
					v =
						pop: doc['Population of service area']
						circulation: doc['Circulation, all items']
					v.percap = v.circulation / v.pop
					emit k, v

# Define the attachments folder for the couchapp
# Change 'attachments' to the specific folder name.
att_folder = (require 'path').join __dirname, 'attachments'

# Load the attachments for the design document to the couchdb server
(require 'couchapp').loadAttachments design_doc, att_folder

# Export the design doc object for other nodejs modules to use
module.exports = design_doc
